const _ = require('lodash');
const async = require('async');
const services = require('../../services');

const commonService = services.common;

function getList(req, res, callback) {
  //   const params = req.query;
  //   const pageId = params.pageId;
  const Keywords = req.query.Keywords;
  const formId = req.query.formId;
  const { WfForm: formModel, WfTemplate: templateModel } = commonService.getModels();
  const option = {
    deleted: false,
  };
  formId ? option.formId = formId : '';
  Keywords ? option.subject = { like: `%${Keywords}%` } : '';
  const templateList = (next) => {
    templateModel.find({ where: option, include: 'form' }, next);
  };
  async.parallel({
    templateList,
    formList: async.apply(commonService.getList, formModel),
  }, (error, result) => callback(error, _.assign(result)));
}

function saveDetail(req, res, callback) {
  const { WfTemplate: templateModel } = commonService.getModels();
  const params = req.body;
  params.id = params.id == 0 ? null : params.id;
  const saveDetail = (next) => {
    templateModel.upsert(params, next);
  };
  async.waterfall([saveDetail], callback);
}

function deleteDatail(req, res, callback) {
  const { WfTemplate: templateModel } = commonService.getModels();
  const id = req.body.id;
  const deleteDetail = (next) => {
    templateModel.update({ id }, { deleted: true }, next);
  };
  async.waterfall([deleteDetail], callback);
}

module.exports = {
  getList,
  saveDetail,
  deleteDatail,
};
